<?php
/**
 * Created by PhpStorm.
 * User: 68008000
 * Date: 2017/12/5
 * Time: 16:11
 */

namespace app\admin\controller;


use think\Controller;

/**
 * Class Group
 * @package app\admin\controller
 * 权限管理之用户组管理
 */
class Group extends Controller
{
    protected $db;
    public function __construct()
    {
        parent::__construct();
        $this->db = new \app\common\model\Group();
    }

    //主页
    public function index(){
        $data = db('authgroup')->select();
        //1视图
        return view('',compact('data'));
    }
    //添加
    public function add()
    {
        $id = input('param.id');
        //2获取规则数据
        $ruleData = db('auth_rule')->select();
        //将pid相同的数据放在一起
        $newArr = [];
        foreach ($ruleData as $k => $v) {
            $newArr[$v['nav']][] = $v;
        }
        //3组一个新数组
        $newArr2 = [];
        foreach ($newArr as $k => $v) {
            $newArr2[] = [
                'name' => db('auth_rule')->where('nav', $k)->value('nav'),
                'rule' => $v
            ];
        }
            $oldData['title'] = [];
            //4添加
            if (request()->isPost()) {
                $data = input('post.');
                $res = $this->db->add($data);
                if ($res['valid']) {
                    $this->success($res['msg'], 'index');
                } else {
                    $this->error($res['msg']);
                }
            }
        //1视图
        return view('', compact('newArr2'));
    }
    //编辑
    public function edit(){
        $id = input('param.id');
        //2获取规则数据
        $ruleData = db('auth_rule')->select();
        //将pid相同的数据放在一起
        $newArr = [];
        foreach ($ruleData as $k => $v) {
            $newArr[$v['nav']][] = $v;
        }
        //3组一个新数组
        $newArr2 = [];
        foreach ($newArr as $k => $v) {
            $newArr2[] = [
                'name' => db('auth_rule')->where('nav', $k)->value('nav'),
                'rule' => $v
            ];
        }
        //1获取用户组旧数据
        $oldData = db('authgroup')->where('id',$id)->find();
        $oldData['rules'] = explode(',',$oldData['rules']);
        //2编辑
        if(request()->isPost()){
            $data = input('post.');
            $res = $this->db->edit($data);
            if ($res['valid']) {
                $this->success($res['msg'], 'index');
            } else {
                $this->error($res['msg']);
            }
        }
        //1视图
        return view('',compact('newArr2','oldData'));
    }
    //删除
    public function del(){
        $id = input('param.id');
        $res = $this->db->del($id);
        if ($res['valid']){
            $this->success($res['msg'],'index');
        }else{
            $this->error($res['msg']);
        }
    }
}